﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.DirectoryServices;

namespace ProCodes.Utilities.ActiveDirectory
{
    /// <summary>
    /// http://www.srinivasvangala.com/2011/03/get-all-ad-groups-using-ldap-in-c.html
    /// </summary>
    public partial class ActiveDirectoryManagement
    {
        public static DataTable GetAllActiveDirectoryGroups(string ldapServer, string ldapUserName, string ldapPassWord)
        {
            DataTable dt = new DataTable();
            DataRow dr;


            DirectoryEntry de = new DirectoryEntry(ldapServer);
            de.Username = ldapUserName;
            de.Password = ldapPassWord;
            DirectorySearcher deSearch = new DirectorySearcher(de.Path);

            SearchResultCollection results;
            dt.Columns.Add("GroupName");
            try
            {
                deSearch.Filter = ("(&(objectCategory=group))");
                deSearch.SearchScope = SearchScope.Subtree;
                //deSearch.SizeLimit = 10000;
                //deSearch.PageSize = 1000;
                results = deSearch.FindAll();

                foreach (SearchResult result in results)
                {
                    dr = dt.NewRow();
                    dr["GroupName"] = result.Properties["cn"][0].ToString();
                    dt.Rows.Add(dr);
                }
                de.Close();


            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (deSearch != null)
                {
                    deSearch.Dispose();
                }
                if (de != null)
                {
                    de.Dispose();
                }
            }

            return dt;

        }
    
    }
}
